package liuyao.webutils.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

public class CipherUtil {

    public static void main(String[] args) throws Exception {
        String str = "a1234567";
        System.out.println("字符串：" + str);
        byte[] keyBytes = "AES454-HTJSQ9-IT".getBytes(StandardCharsets.UTF_8);
        String encryptStr = new String(Base64.getEncoder().encode(
                aesEncrypt_256_ECB_Pkcs7Padding(str.getBytes(StandardCharsets.UTF_8), keyBytes)));
        System.out.println("加密后字符串：" + encryptStr);
        String decryptStr = new String(
                aesDecrypt_256_ECB_Pkcs7Padding(Base64.getDecoder().decode(encryptStr), keyBytes));
        System.out.println("解密后字符串：" + decryptStr);

        byte[] bytes = aesEncrypt_256_ECB_Pkcs7Padding(str.getBytes(StandardCharsets.UTF_8), keyBytes);
        encryptStr = new String(bytes);
        System.out.println("加密后字符串：" + encryptStr);
        byte[] bytes1 = aesDecrypt_256_ECB_Pkcs7Padding(bytes, keyBytes);
        decryptStr = new String(bytes1);
        System.out.println("解密后字符串：" + decryptStr);
    }

    private static final String SECRET = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES加密ECB模式PKCS7Padding填充方式
     * @param str 字符串
     * @param key 密钥
     * @return 加密字符串
     * @throws Exception 异常信息
     */
    public static byte[] aesEncrypt_256_ECB_Pkcs7Padding(byte[] data, byte[] keyBytes) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        return cipher.doFinal(data);
    }

    /**
     * AES解密ECB模式PKCS7Padding填充方式
     * @param str 字符串
     * @param key 密钥
     * @return 解密字符串
     * @throws Exception 异常信息
     */
    public static byte[] aesDecrypt_256_ECB_Pkcs7Padding(byte[] data, byte[] keyBytes) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        return cipher.doFinal(data);
    }
}
